<?php

namespace Mobile\Controller;

/**
 * Description 统计控制器相关业务接口
 * 
 * @author songanwei
 * @date 2016-1-22
 */
class ReportController extends ParentController {

    protected function _initialize() {
        parent::_initialize();
        $this->validateUtil = new \Org\Util\Validate();
        //检查操作权限
        $adminAuthorityLogic = A('Common/AdminAuthority', 'Logic');
        $hotel = I('request.hotel');
        //检查客栈是否已过期
        $hotelLogic = A('Common/Hotel', 'Logic');
        $hotelLogic->checkHotelActive($hotel);
        $adminAuthorityLogic->check($hotel);
    }

    /**
     * @description 获取统计概览数据||根据类型获取相应数据
     * @modify songanwei 2016-01-22
     */
    public function summary() {
        $params = I('post.');
        $validateRule = array(
            'userId' => 'notnull,notempty,id',
            'hotel' => 'notnull,notempty,id',
            'token' => 'notnull,notempty',
            'type' => 'notnull,notempty,id'
        );
        $this->ajaxValidateReturn($this->validateUtil, $params, $validateRule);
        $userId = $params['userId'];
        $token = $params['token'];
        $hotelId = $params['hotel'];
        $type = $params['type'];

        $this->checkMobileToken($userId, $token);
        $reportLogic = A('Common/Report', 'Logic');

        //计算当前一周数据
        //定义一周数据
        switch ($type) {
            case '1':
                $startDate = date('Y-m-d', strtotime('Sunday last week'));
                $endDate = date('Y-m-d', strtotime('Saturday this week'));
                break;
            case '4':
                $startDate = date('Y-m-d', strtotime('Sunday -2 week'));
                $endDate = date('Y-m-d', strtotime('Saturday last week'));
                break;
            case '5':
                $startDate = date('Y-m-01', strtotime('this month'));
                $endDate = date('Y-m-t', strtotime('this month'));
                break;
            case '6':
                $startDate = date('Y-m-01', strtotime('last month'));
                $endDate = date('Y-m-t', strtotime('last month'));
                break;
        }
        $detail = array();

        // 多语言判断
        $lang = LANG_SET;
        $lang = isset($lang) ? $lang : 'zh_cn';
        switch ($lang) {
            case 'zh_cn':
                $weekArray = array("周日", "周一", "周二", "周三", "周四", "周五", "周六");
                break;
            case 'zh_tw':
                $weekArray = array("週日", "週一", "週二", "週三", "週四", "週五", "週六");
                break;
            case 'en_us':
                $weekArray = array("Sun", "Mon", "Tues", "Wed", "Thur", "Fri", "Sat");
                break;
            default:
                $weekArray = array("周日", "周一", "周二", "周三", "周四", "周五", "周六");
                break;
        }

        $currentDate = date('Y-m-d');
        $version = getVersion(array('2.0.00'));
        //初始化日期间隔天数
        if ($type == 2 | $type == 3) {
            switch ($type) {
                case 2:
                    //统计昨天数据
                    $yesterdayDate = date('Y-m-d', strtotime('-1 days'));
                    //查询昨天数据
                    $summary = $reportLogic->getSummary($hotelId, $yesterdayDate);
                    $roomReport = $reportLogic->getRoomReport($hotelId, $yesterdayDate);
                    $detail[] = array(
                        'date' => $yesterdayDate,
                        'day' => $weekArray[date('w', strtotime($yesterdayDate))],
                        'price' => $roomReport['price']
                    );
                    $startDate = $endDate = $yesterdayDate;
                    break;
                case 3:
                    //统计今天数据
                    //查询今天数据
                    $summary = $reportLogic->getTodaySummary($hotelId, $currentDate);
                    $roomReport = $reportLogic->getTodayRoomReport($hotelId, $currentDate);
                    $detail[] = array(
                        'date' => $currentDate,
                        'day' => $weekArray[date('w', strtotime($currentDate))],
                        'price' => $roomReport['price']
                    );
                    $startDate = $endDate = $currentDate;
                    break;
            
            }
        } else {
            $summary = $reportLogic->getSummary($hotelId, $startDate, $endDate);
            $roomReport = $reportLogic->getRoomReport($hotelId, $startDate, $endDate);

            // v2.0.00计算结束日期在未来,不进行计算
            if ($version >= '2.0.00') {
                $endDate = $endDate > $currentDate ? $currentDate : $endDate;
            }
            //计算一个周每一天的入住率以及相关总价情况
            for ($i = 0; $i < ceil((strtotime($endDate . ' 23:59:59') - strtotime($startDate)) / 86400); $i++) {
                $dateIndex = date('Y-m-d', strtotime($startDate) + 86400 * $i);
                if ($dateIndex == date('Y-m-d')) {
                    $tempRoomReport = $reportLogic->getTodayRoomReport($hotelId, $dateIndex);
                } else {
                    $tempRoomReport = $reportLogic->getRoomReport($hotelId, $dateIndex);
                }
                $detail[] = array(
                    'date' => $dateIndex,
                    'day' => $weekArray[date('w', strtotime($dateIndex))],
                    'price' => $tempRoomReport['price'],
                );
            }
        }
        //计算收入
        $data['income'] = $summary['receipt'] + $summary['deposit'];
        //计算支出
        $data['outcome'] = $summary['refund'] + $summary['refundDeposit'];
        //surplus总结余
        $data['surplus'] = $data['income'] - $data['outcome'];
        $data['occupancyNumber'] = $roomReport['checkInCount'];
        //计算入住率
        $data['occupancyRate'] = round(($roomReport['checkInCount'] / $roomReport['roomTotal']) * 100, 2) . '%';
        //计算入住数
        $data['price'] = $roomReport['price'];
        $data['detail'] = $detail;
        $data['startDate'] = $startDate;
        $data['endDate'] = $endDate;

        //返回数据
        returnJson(200, 200, $data);
    }


    /**
     * 首页获取客栈当天信息
     */
    public function brief() {
        $params = I('post.');
        $validateRule = array(
            'userId' => 'notnull,notempty,id',
            'hotel' => 'notnull,notempty,id',
            'token' => 'notnull,notempty',
        );
        $validatePass = $this->ajaxValidateReturn($this->validateUtil, $params, $validateRule);
        if (!$validatePass) {
            return;
        }

        $userId = $params['userId'];
        $token = $params['token'];
        $this->checkMobileToken($userId, $token);
        
        $hotelId = $params['hotel'];
        $currentDate = date('Y-m-d');
        $reportLogic = A('Common/Report', 'Logic');
        $todaySummary = $reportLogic->getTodaySummary($hotelId, $currentDate);
        $todayRoomReport = $reportLogic->getTodayRoomReport($hotelId, $currentDate);
        if (D('HourRoomInit')->getInfo($hotelId)) {
            $todayHourSummary = $reportLogic->getTodayHourSummary($hotelId, $currentDate);
            $todayHourRoomReport = $reportLogic->getTodayHourRoomReport($hotelId, $currentDate);
            $todayRoomReport['notCheckIn'] += $todayHourRoomReport['notCheckIn']; 
            $todayRoomReport['checkInCount'] += $todayHourRoomReport['checkInCount'];
            $todaySummary['receipt'] += $todayHourSummary['receipt'];
            $todayRoomReport['notSold'] -= $todayHourRoomReport['rest'];
        }
        //返回数据
        returnJson(200, 200, array(
            'payedOrder' => $todayRoomReport['notCheckIn'],
            'checkinedOrder' => $todayRoomReport['checkInCount'],
            'emptyRoom' => $todayRoomReport['notSold'],
            'todayReceipt' => round($todaySummary['receipt'], 2),
            'occupancyRate' => round($todayRoomReport['occupancyRate'] * 100, 2) . '%',
            'averagePrice' => round($todayRoomReport['price'], 2),
        ));
    }

    /**
     * 首页获取客栈当天信息
     */
    public function statistics() {
        $params = I('post.');
        $validateRule = array(
            'userId' => 'notnull,notempty,id',
            'hotel' => 'notnull,notempty,id',
            'token' => 'notnull,notempty',
            'type' => 'notnull,notempty,id',
            'startDate' => 'notnull,notempty,isDate',
            'endDate' => 'notnull,notempty,isDate',

        );
        $this->ajaxValidateReturn($this->validateUtil, $params, $validateRule);
        $userId = $params['userId'];
        $token = $params['token'];
        $hotelId = $params['hotel'];
        $type = $params['type'];
        $startDate = $params['startDate'];
        $endDate = $params['endDate'];
        $reportLogic = A('Common/Report', 'Logic');
        $roomReport = $reportLogic->getBucketReport($hotelId, $startDate, $endDate, $type);
        //计算支出
        //返回数据
        returnJson(200, 200, $roomReport);
    }
}
